package com.huyi.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CountDownLatch：实时通知，实时获取消息
 * 
 * 
 * @author shengli.hu
 *
 */
public class CountDownLatchDemo {

	public static void main(String[] args) throws InterruptedException {
		
		// 次数1：代表通知一次即可
		CountDownLatch countDownLatch = new CountDownLatch(1);
		
		AtomicInteger count = new AtomicInteger(0);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread() + "启动开始");
				if(count.get() < 5) {
					try {
						countDownLatch.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println(Thread.currentThread() + "收到通知，暂停操作。。");
				try {
					throw new InterruptedException(Thread.currentThread() + "xxx");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}, "t1").start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<10;i++) {
					count.incrementAndGet();
					System.out.println(Thread.currentThread() + "计数器count = " +count);
					if(count.get() == 5) {
						System.out.println(Thread.currentThread() + "通知唤醒操作。。。");
						countDownLatch.countDown();
					}
				}
			}
		}, "t2").start();
	}
}


